<template>
  <div> <el-tabs v-model="signatureMethod" type="border-card">
      <el-tab-pane label="手写签名" name="draw">
        <canvas ref="signatureCanvas" width="550" height="200" style="border: 1px solid #ccc;"></canvas>
        <div style="margin-top: 10px;">
          <el-button @click="clearSignatureLocal">清空</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="文本签名" name="text">
        <el-input v-model="textSignature" placeholder="请输入您的姓名"></el-input>
        <el-select v-model="signatureFont" placeholder="选择字体" style="margin-top: 10px;">
          <el-option label="楷体" value="KaiTi"></el-option>
          <el-option label="行书" value="XingShu"></el-option>
        </el-select>
        <div class="text-signature-preview" :style="{ fontFamily: signatureFont }">{{ textSignature || '预览签名' }}</div>
      </el-tab-pane>
      <el-tab-pane label="上传签名图片" name="upload">
        <el-upload
          class="upload-demo"
          drag
          action="#"
          :auto-upload="false"
          :on-change="handleSignatureImageUpload"
          :show-file-list="false"
          accept="image/*"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖拽文件到此 或 <em>点击上传</em></div>
        </el-upload>
        <img v-if="uploadedSignatureImage" :src="uploadedSignatureImage" alt="上传签名预览" style="max-width: 100px; max-height: 100px; margin-top: 10px;" />
      </el-tab-pane>
    </el-tabs>
    <div class="signature-actions">
      <el-button @click="emit('clear')">取消</el-button>
      <el-button type="primary" @click="confirmSignature">确认签名</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';

const emit = defineEmits(['signed', 'clear']);

const signatureMethod = ref('draw');

const signatureCanvas = ref(null);
let ctx = null;
let isDrawing = false;

const textSignature = ref('');
const signatureFont = ref('KaiTi');

const uploadedSignatureImage = ref(null);

onMounted(() => {
  nextTick(() => {
    initCanvas();
  });
});

const initCanvas = () => {
  if (signatureCanvas.value) {
    ctx = signatureCanvas.value.getContext('2d');
    ctx.lineWidth = 2;
    ctx.lineCap = 'round';
    ctx.strokeStyle = '#000';

    signatureCanvas.value.addEventListener('mousedown', startDrawing);
    signatureCanvas.value.addEventListener('mousemove', draw);
    signatureCanvas.value.addEventListener('mouseup', stopDrawing);
    signatureCanvas.value.addEventListener('mouseleave', stopDrawing);

    signatureCanvas.value.addEventListener('touchstart', startDrawing);
    signatureCanvas.value.addEventListener('touchmove', draw);
    signatureCanvas.value.addEventListener('touchend', stopDrawing);
  }
};

const getCanvasPosition = (e) => {
  const rect = signatureCanvas.value.getBoundingClientRect();
  if (e.touches && e.touches[0]) {
    return {
      x: e.touches[0].clientX - rect.left,
      y: e.touches[0].clientY - rect.top
    };
  } else {
    return {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    };
  }
};

const startDrawing = (e) => {
  e.preventDefault();
  isDrawing = true;
  const pos = getCanvasPosition(e);
  ctx.beginPath();
  ctx.moveTo(pos.x, pos.y);
};

const draw = (e) => {
  e.preventDefault();
  if (!isDrawing) return;
  const pos = getCanvasPosition(e);
  ctx.lineTo(pos.x, pos.y);
  ctx.stroke();
};

const stopDrawing = () => {
  isDrawing = false;
  ctx.closePath();
};

const clearSignatureLocal = () => {
  if (ctx) {
    ctx.clearRect(0, 0, signatureCanvas.value.width, signatureCanvas.value.height);
  }
  uploadedSignatureImage.value = null;
  textSignature.value = '';
};

const handleSignatureImageUpload = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    uploadedSignatureImage.value = e.target.result;
    ElMessage.success('签名图片已上传');
  };
  reader.readAsDataURL(file.raw);
};

const confirmSignature = () => {
  let signatureData = null;
  if (signatureMethod.value === 'draw' && signatureCanvas.value) {
    signatureData = signatureCanvas.value.toDataURL('image/png');
    const blankCanvas = document.createElement('canvas');
    blankCanvas.width = signatureCanvas.value.width;
    blankCanvas.height = signatureCanvas.value.height;
    if (signatureData === blankCanvas.toDataURL('image/png')) {
      ElMessage.warning('请在画布上绘制您的签名！');
      return;
    }
  } else if (signatureMethod.value === 'text' && textSignature.value) {
    const tempCanvas = document.createElement('canvas');
    tempCanvas.width = 300;
    tempCanvas.height = 100;
    const tempCtx = tempCanvas.getContext('2d');
    tempCtx.font = `40px ${signatureFont.value}`;
    tempCtx.fillStyle = '#000';
    tempCtx.fillText(textSignature.value, 10, 60);
    signatureData = tempCanvas.toDataURL('image/png');
    if (!textSignature.value) {
      ElMessage.warning('请输入您的姓名作为文本签名！');
      return;
    }
  } else if (signatureMethod.value === 'upload' && uploadedSignatureImage.value) {
    signatureData = uploadedSignatureImage.value;
  } else {
    ElMessage.warning('请选择一种签名方式并完成签名！');
    return;
  }

  emit('signed', signatureData);
};
</script>

<style scoped>
canvas {
  touch-action: none;
}
.text-signature-preview {
  margin-top: 15px;
  border: 1px dashed #ccc;
  min-height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  color: #333;
}
.signature-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>